package com.morn.fanfou.api;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.james.mime4j.util.CharsetUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.morn.fanfou.exception.FanfouException;
import com.morn.fanfou.http.CountingMultipartEntity;
import com.morn.fanfou.http.CountingMultipartEntity.ProgressListener;
import com.morn.fanfou.image.ImageDownload;
import com.morn.fanfou.model.AccountNotification;
import com.morn.fanfou.model.Conversation;
import com.morn.fanfou.model.Message;
import com.morn.fanfou.model.OAuthToken;
import com.morn.fanfou.model.Status;
import com.morn.fanfou.model.Trends;
import com.morn.fanfou.model.User;
import com.morn.fanfou.util.UrlStr;

public class Fanfou extends FanfouSupport {

	private OAuthToken oAuthToken;

	public Fanfou(Context context) {
		super(context);
	}

	public OAuthToken getOAuthToken(String username, String password) {
		return null;
	}

	@Override
	public OAuthToken getOAuthToken() {
		return oAuthToken;
	}

	public List<Status> getPhotoStatus(String sinceId, String maxId, String page, String userId) throws Exception {
		String str = doHttpGet(UrlStr.PHOTOS_USER_TIMELINE, new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId), new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair("mode", "lite"), new BasicNameValuePair(
						"id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getHomeStatusList(String sinceId, String maxId, String page, String userId)
			throws JSONException, FanfouException {
		String str = doHttpGet(UrlStr.STATUSES_HOME_TIMELINE, new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId), new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair("mode", "lite"), new BasicNameValuePair(
						"id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getRepliesStatusList(String sinceId, String maxId, String page, String userId)
			throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_REPLIES, new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId), new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair("mode", "lite"), new BasicNameValuePair(
						"id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getUserStatusList(String userId, String sinceId, String maxId, String page)
			throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_USER_TIMELINE, new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId), new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("page", page), new BasicNameValuePair("mode", "lite"), new BasicNameValuePair(
						"id", userId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getPublicStatusList(String sinceId, String maxId) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_PUBLIC_TIMELINE, new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("since_id", sinceId), new BasicNameValuePair("max_id", maxId),
				new BasicNameValuePair("mode", "lite"));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<Status> getContextStatusList(String id) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_CONTEXT_TIMELINE, new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("id", id), new BasicNameValuePair("mode", "lite"));
		return Status.getStatusList(new JSONArray(str));
	}

	public Status getStatus(String statusId) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_SHOW, new BasicNameValuePair("format", "html"), new BasicNameValuePair(
				"id", statusId), new BasicNameValuePair("mode", "lite"));
		return new Status(new JSONObject(str));
	}

	public List<Status> getFavorites(String userId, String page) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.FAVORITES, new BasicNameValuePair("id", userId), new BasicNameValuePair("page",
				page), new BasicNameValuePair("format", "html"), new BasicNameValuePair("mode", "lite"));
		return Status.getStatusList(new JSONArray(str));
	}

	// ------------------------------------------

	public String updateStatus(String str, String reStatusId, String reUserId, String repostId, String location)
			throws FanfouException {
		return doHttpPost(UrlStr.STATUSES_POST_UPDATE, new BasicNameValuePair("status", str), new BasicNameValuePair(
				"in_reply_to_status_id", reStatusId), new BasicNameValuePair("in_reply_to_user_id", reUserId),
				new BasicNameValuePair("repost_status_id", repostId), new BasicNameValuePair("source", null),
				new BasicNameValuePair("location", location));
	}

	public String deleteStatus(String idStr) throws FanfouException {
		return doHttpPost(UrlStr.STATUSES_POST_DESTROY, new BasicNameValuePair("id", idStr), new BasicNameValuePair(
				"mode", "lite"), new BasicNameValuePair("format", "html"));
	}

	// ----

	public String uploadStatus(ContentBody photo, String description, ProgressListener progressListener)
			throws FanfouException {
		String urlStr = BASEURL + UrlStr.STATUSES_POST_PHOTOS;
		HttpPost httpPost = new HttpPost(urlStr);
		String returnStr = null;
		CountingMultipartEntity reqEntity = new CountingMultipartEntity(progressListener);

		reqEntity.addPart("photo", photo);
		try {
			if (description != null && description.length() > 0)
				reqEntity.addPart("status", new StringBody(description, CharsetUtil.getCharset("UTF-8")));
			httpPost.setEntity(reqEntity);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity resEntity = response.getEntity();
			returnStr = EntityUtils.toString(resEntity);
		} catch (Exception e) {
			httpPost.abort();
			e.printStackTrace();
			throw new FanfouException(e.getMessage());

		}
		return returnStr;
	}

	public List<Status> searchStatus(String q, String maxId) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.SEARCH_STATUSES, new BasicNameValuePair("q", q), new BasicNameValuePair("format",
				"html"), new BasicNameValuePair("mode", "lite"), new BasicNameValuePair("max_id", maxId));
		return Status.getStatusList(new JSONArray(str));
	}

	public List<User> searchUser(String q, String maxId) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.SEARCH_USERS, new BasicNameValuePair("q", q), new BasicNameValuePair("format",
				"html"), new BasicNameValuePair("mode", "lite"), new BasicNameValuePair("max_id", maxId));
		// TODO total_number: 86
		return User.getUserList(new JSONArray(str));
	}

	public List<User> getFriends(String userId, String page) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_FRIENDS, new BasicNameValuePair("id", userId), new BasicNameValuePair(
				"page", page));
		return User.getUserList(new JSONArray(str));
	}

	public List<User> getFollows(String userId, String page) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.STATUSES_FOLLOWERS, new BasicNameValuePair("id", userId), new BasicNameValuePair(
				"page", page), new BasicNameValuePair("mode", "lite"));
		return User.getUserList(new JSONArray(str));
	}

	public User getUser(String userId) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.USERS_SHOW, new BasicNameValuePair("id", userId), new BasicNameValuePair("mode",
				"lite"));
		return new User(new JSONObject(str));
	}

	public List<Message> getReceivedMessage(String maxId) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.MESSAGES_DIRECT, new BasicNameValuePair("max_id", maxId));
		return Message.getMessageList(new JSONArray(str));
	}

	public List<Message> getSendMessage(String maxId) throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.MESSAGES_DIRECT_SENT, new BasicNameValuePair("max_id", maxId));
		return Message.getMessageList(new JSONArray(str));
	}

	public Message sendMessage(String userId, String text, String replyId) throws FanfouException, JSONException {
		String str = doHttpPost(UrlStr.MESSAGES_NEW, new BasicNameValuePair("user", userId), new BasicNameValuePair(
				"text", text), new BasicNameValuePair("mode", "lite"), new BasicNameValuePair("text", text),
				new BasicNameValuePair("in_reply_to_id", replyId));
		return new Message(new JSONObject(str));
	}

	public String deleteMessage(String messageId) throws FanfouException {
		return doHttpPost(UrlStr.MESSAGES_DESTROY, new BasicNameValuePair("id", messageId));
	}

	//
	public String createFavorites(String statusId) throws FanfouException {
		return doHttpPost(UrlStr.FAVORITES_CREATE, new BasicNameValuePair("id", statusId), new BasicNameValuePair(
				"mode", "lite"));
	}

	public String deleteFavorites(String statusId) throws FanfouException {
		return doHttpPost(UrlStr.FAVORITES_DESTROY, new BasicNameValuePair("id", statusId), new BasicNameValuePair(
				"mode", "lite"));
	}

	public User createFriendships(String userId) throws FanfouException, JSONException {
		String str = doHttpPost(UrlStr.FRIENDSHIPS_CREATE, new BasicNameValuePair("id", userId),
				new BasicNameValuePair("mode", "lite"));
		return new User(new JSONObject(str));
	}

	public User deleteFriendships(String userId) throws FanfouException, JSONException {
		String str = doHttpPost(UrlStr.FRIENDSHIPS_DESTROY, new BasicNameValuePair("id", userId),
				new BasicNameValuePair("mode", "lite"));
		return new User(new JSONObject(str));
	}

	public boolean isFriendships(String user_a, String user_b) throws FanfouException {
		String str = doHttpGet(UrlStr.FRIENDSHIPS_EXISTS, new BasicNameValuePair("user_a", user_a),
				new BasicNameValuePair("user_b", user_b));
		return "true".equals(str);
	}

	public List<Trends> getTrendsList() throws FanfouException, JSONException {
		String str = doHttpGet(UrlStr.URL_API_TRENDS);
		return Trends.getTrendsList(new JSONObject(str));
	}

	public AccountNotification getAccountNotification() throws Exception {
		String str = doHttpGet(UrlStr.ACCOUNT_NOTIFICATION);
		return new AccountNotification(new JSONObject(str));
	}

	public List<Conversation> getConversationList(String count, String page) throws Exception {
		String str = doHttpGet(UrlStr.MESSAGES_CONVERSATION_LIST, new BasicNameValuePair("count", count),
				new BasicNameValuePair("page", page), new BasicNameValuePair("mode", "lite"));
		Log.i("testFanfou", str);
		return Conversation.getConversationList(new JSONArray(str));
	}

	public List<Message> getConversation(String userId, String max_id, String count, String page) throws Exception {
		String str = doHttpGet(UrlStr.MESSAGES_CONVERSATION, new BasicNameValuePair("id", userId),
				new BasicNameValuePair("count", count), new BasicNameValuePair("max_id", max_id),
				new BasicNameValuePair("page", page), new BasicNameValuePair("mode", "lite"));
		return Message.getMessageList(new JSONArray(str));
	}

	public User verifyAccount() throws Exception {
		String str = doHttpGet(UrlStr.ACCOUNT_VERIFY_CREDENTIALS, new BasicNameValuePair("format", "html"),
				new BasicNameValuePair("mode", "lite"));
		return new User(new JSONObject(str));
	}

	public void clearImage() {
		// imageDownload.deleteImage(ImageDownload.cacheDir);
	}

}
